<template>
  <div class="entrust-list-container">


    <a-page-header class="demo-page-header" style="border: 1px solid rgb(235, 237, 240); margin-bottom: 24px;"
      title="委托案件列表" :sub-title="`${totalCasesCount}条数据`" @back="() => $router.go(-1)">
      <p class="date-range-info">
        显示今日待委托案件数据，按批次分组显示
      </p>
      <template #extra>
        <a-button @click="handleRefresh">
          <span>刷新</span>
        </a-button>
        <a-button type="primary" :disabled="isEntrustButtonDisabled" @click="handleEntrust">
          委案
        </a-button>
      </template>
    </a-page-header>

    <div class="flex justify-between w-full h-full new-layout" style="height: calc(100% - 156px); overflow: auto;">
      <div v-if="currentTableData.length > 0" class="w-1/5 h-full pr-5 sticky-sidebar">
        <a-card class="h-full position-relative" type="inner" :body-style="{ padding: '20px' }"
          style="margin-bottom: 24px; box-shadow: none;">

          <a-menu style="width: 100%" mode="vertical" :selected-keys="[activeTabKey]" @click="handleMenuClick"
            :items="menuItems" />

        </a-card>
      </div>
      <div class="w-4/5 h-full overflow-auto">
        <a-spin :spinning="loading" tip="加载中...">
          <!-- 无数据时显示 -->
          <div v-if="currentTableData.length === 0 && !loading" class="no-data-container">
            <a-empty style="margin-top: 100px;" image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
              :image-style="{ height: '120px', display: 'flex',flexDirection: 'column',alignItems: 'center' }">
              <template #description>
                <span class="empty-description">暂无委托案件数据</span>
                <p class="empty-tip">今日暂无待委托的案件，请稍后再试或联系管理员</p>
              </template>
            
            </a-empty>
          </div>

          <!-- 有数据时显示表格 -->
          <a-table :bordered="true" v-else :columns="columns" :data-source="currentTableData" :pagination="false"
            :row-selection="rowSelection" row-key="loanId" :scroll="{ y: 'calc(100vh - 300px)' }" size="small">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'customerInfo'">
                <div class="customer-info">
                  <div class="customer-name">{{ record.realName }}</div>
                  <div class="customer-mobile">{{ record.mobile }}</div>
                </div>
              </template>
              <template v-else-if="column.key === 'periodInfo'">
                <div class="period-info">
                  <div>逾期天数：{{ record.overdueDays }} </div>
                  <div>
                    <span>{{ record.loanCollectionPeriod }}期</span> / <span>{{ record.loanTotalPeriod }}期</span>
                  </div>
                </div>
              </template>
              <template v-else-if="column.key === 'amountInfo'">
                <div class="amount-info">
                  <div>待还金额：{{ formatAmount(record.totalNoRepayRepay) }}</div>
                  <div>实还金额：{{ formatAmount(record.realBackedRepay) }}</div>
                  <div>减免金额：{{ formatAmount(record.mitigateBackedRepay) }}</div>
                </div>
              </template>
              <template v-else-if="column.key === 'lastRepayDate'">
                {{ formatDate(record.lastBackedDate) }}
              </template>
              <template v-else-if="column.key === 'projectStatus'">
                <Tag :color="getProjectStatusColor(record.state)">
                  {{ getProjectStatusText(record.state) }}
                </Tag>
              </template>
              <template v-else-if="column.key === 'distributeStatus'">
                <Tag :color="getDistributeStatusColor(record.distributeState)">
                  {{ getDistributeStatusText(record.distributeState) }}
                </Tag>
              </template>
            </template>
          </a-table>
        </a-spin>
      </div>
    </div>
    <!-- 委案弹框 -->
    <a-modal v-model:open="isEntrustModalVisible" title="委案" width="600px" :ok-text="'提交'" :cancel-text="'取消'"
      @ok="handleEntrustConfirm" @cancel="handleEntrustCancel">
      <a-form :model="entrustForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="客户数量">
          <a-input-number v-model:value="entrustForm.clients" :disabled="true" style="width: 100%" />
        </a-form-item>

        <a-form-item label="项目数量">
          <a-input-number v-model:value="entrustForm.loans" :disabled="true" style="width: 100%" />
        </a-form-item>

        <a-form-item label="委案商" :rules="[{ required: true, message: '请选择委案商' }]">
          <a-select v-model:value="entrustForm.entrustBId" placeholder="请选择委案商" style="width: 100%">
            <a-select-option v-for="item in entrustList" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="委案批次">
          <a-radio-group v-model:value="entrustForm.batchOption">
            <a-radio value="new">新增</a-radio>
            <a-radio value="select">选择</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item v-if="entrustForm.batchOption === 'new'" label="委案批次名称"
          :rules="[{ required: true, message: '请输入委案批次名称' }]">
          <a-input v-model:value="entrustForm.batchName" placeholder="请输入委案批次名称" />
        </a-form-item>

        <a-form-item label="跳过同客户限制">
          <a-checkbox v-model:checked="entrustForm.isInvalidRule">
            跳过
          </a-checkbox>
        </a-form-item>
      </a-form>
    </a-modal>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { message, Tag } from 'ant-design-vue';
import { getCaseList, countEntrustClient, getEntrustByAId, entrustClient } from '../server/api';
import type { GetCaseListParams, CaseRecord } from '../server/type';
import { useScheduledTask } from '../composables/useScheduledTask';
import dayjs from 'dayjs';

// 案件数据
const casesData = ref<CaseRecord[]>([]);
const activeTabKey = ref<string>('');

// 表格列配置
const columns = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    customRender: ({ index }: { index: number }) => {
      return index + 1;
    }
  },
  {
    title: '客户LoanId',
    dataIndex: 'loanId',
    key: 'loanId',
    width: 150,
    align: 'center'
  },
  {
    title: '借钱项目产品线',
    dataIndex: 'productTypeName',
    key: 'productTypeName',
    width: 150,
    align: 'center'
  },
  {
    title: '客户信息',
    key: 'customerInfo',
    width: 150,
    align: 'center'
  },
  {
    title: '入库期数/分期数',
    key: 'periodInfo',
    width: 150,
    align: 'center'
  },
  {
    title: '项目编号批次',
    dataIndex: 'batchName',
    key: 'batchName',
    width: 150,
    align: 'center'
  },
  {
    title: '待还金额实还/减免金额',
    key: 'amountInfo',
    width: 200,
    align: 'center'
  },
  {
    title: '首次入库最后还款',
    key: 'urgeTime',
    width: 150,
    align: 'center',
    customRender: ({ record }: { record: any }) => {
      return record.urgeTime ? dayjs(record.urgeTime).format('YYYY-MM-DD HH:mm:ss') : '-';
    }
  },
  {
    title: '项目状态',
    key: 'projectStatus',
    width: 120,
    align: 'center'
  },
  {
    title: '分案状态',
    key: 'distributeStatus',
    width: 120,
    align: 'center'
  }
];

// 行选择配置
const selectedRowKeys = ref<string[]>([]);
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (selectedKeys: string[]) => {
    selectedRowKeys.value = selectedKeys;
    // 检查是否全选
    const currentGroup = groupedCases.value[activeTabKey.value] || [];
    isEntrustButtonDisabled.value = selectedKeys.length !== currentGroup.length || selectedKeys.length === 0;
  },
  onSelectAll: (selected: boolean, selectedRows: CaseRecord[], changeRows: CaseRecord[]) => {
    console.log('全选状态:', selected, '选中的行:', selectedRows, '变化的行:', changeRows);
    const currentGroup = groupedCases.value[activeTabKey.value] || [];
    isEntrustButtonDisabled.value = !selected || currentGroup.length === 0;
  }
};

// 委案相关状态
const isEntrustModalVisible = ref(false);
const isEntrustButtonDisabled = ref(true);
const entrustForm = ref({
  batchId: '', // 委案批次ID(选择的时候才会有内容)
  clients: 0,
  loans: 0,
  entrustBId: '', // 委案商ID
  batchOption: 'new', // 'select' | 'new'
  batchName: '', // 委案批次名称
  isInvalidRule: true, // 是否跳过同客户限制
  loanIds: [] as string[] // 选中的案件ID列表
});
const entrustList = ref<any[]>([]);

// 加载状态
const loading = ref(false);

// 定时任务composables
const { executeTask: executeScheduledTask } = useScheduledTask();

// 调试模式（可以通过环境变量控制）
const debugMode = ref(import.meta.env.DEV);

// 按批次分组的数据
const groupedCases = computed(() => {
  const groups: Record<string, CaseRecord[]> = {};
  casesData.value.forEach(caseItem => {
    const batchName = caseItem.batchName || '未分组';
    if (!groups[batchName]) {
      groups[batchName] = [];
    }
    groups[batchName].push(caseItem);
  });

  // 对每个批次内的数据进行排序，待审核的放到最前面
  Object.keys(groups).forEach(batchName => {
    groups[batchName].sort((a, b) => {
      // 获取状态码进行比较
      const getStateCode = (state: any) => {
        if (typeof state === 'object' && state.code) {
          return state.code;
        }
        return typeof state === 'string' ? state : '';
      };

      const stateA = getStateCode(a.state);
      const stateB = getStateCode(b.state);

      // 待审核状态优先
      if (stateA === 'PENDING_AUDIT' && stateB !== 'PENDING_AUDIT') return -1;
      if (stateB === 'PENDING_AUDIT' && stateA !== 'PENDING_AUDIT') return 1;

      // 其他状态按原有顺序
      return 0;
    });
  });

  return groups;
});

// 生成侧边栏菜单项
const menuItems = computed(() => {
  const items = Object.keys(groupedCases.value).map(batchName => ({
    key: batchName,
    label: `${batchName} (${groupedCases.value[batchName].length}条)`,
    title: batchName
  }));

  // 如果没有数据，显示默认项
  if (items.length === 0) {
    return [{
      key: 'no-data',
      label: '暂无数据',
      title: '暂无数据'
    }];
  }

  return items;
});

// 当前显示的数据
const currentTableData = computed(() => {
  if (activeTabKey.value && groupedCases.value[activeTabKey.value]) {
    return groupedCases.value[activeTabKey.value];
  }
  return [];
});

// 总案件数量
const totalCasesCount = computed(() => {
  return casesData.value.length;
});


// 格式化金额
const formatAmount = (amount: number) => {
  if (amount === null || amount === undefined) return '0.00';
  return (amount / 100).toFixed(2);
};

// 格式化日期
const formatDate = (date: string | number | null) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD');
};

// 获取项目状态文本
const getProjectStatusText = (state: any) => {
  if (typeof state === 'object' && state.message) {
    return state.message;
  }
  return typeof state === 'string' ? state : '未知';
};


// 获取项目状态颜色
const getProjectStatusColor = (state: any) => {
  let statusCode = state;
  if (typeof state === 'object' && state.code) {
    statusCode = state.code;
  }
  const colorMap: Record<string, string> = {
    'INIT': 'blue',
    'PROCESSING': 'processing',
    'COMPLETED': 'success',
    'FAILED': 'error',
    'CANCELLED': 'default'
  };
  return colorMap[statusCode] || 'default';
};

// 获取分案状态文本
const getDistributeStatusText = (distributeState: any) => {
  if (typeof distributeState === 'object' && distributeState.message) {
    return distributeState.message;
  }
  return typeof distributeState === 'string' ? distributeState : '未知';
};

// 获取分案状态颜色
const getDistributeStatusColor = (distributeState: any) => {
  let statusCode = distributeState;
  if (typeof distributeState === 'object' && distributeState.code) {
    statusCode = distributeState.code;
  }
  const colorMap: Record<string, string> = {
    'UNASSIGNED': 'orange',
    'ASSIGNED': 'blue',
    'IN_PROGRESS': 'processing',
    'COMPLETED': 'success',
    'CANCELLED': 'default'
  };
  return colorMap[statusCode] || 'default';
};

/**
 * 格式化批次名称
 * 1. 移除日期后面的 "_数字" 部分（如：20250929_35 -> 20250929）
 * 2. 去除重复的片段（如：农信社-好瑞迪-良庆-好瑞迪 -> 农信社-好瑞迪-良庆）
 * @param batchName 原始批次名称
 * @returns 格式化后的批次名称
 */
const formatBatchName = (batchName: string): string => {
  if (!batchName) return '';

  try {
    // 第一步：移除日期后面的 "_数字" 部分
    // 匹配模式：8位数字_数字 或 8位数字_数字-数字
    let formattedName = batchName.replace(/(\d{8})_\d+(-?\d*)/g, '$1$2');
    
    // 第二步：去除重复的片段（保留第一次出现的）
    // 按 "-" 分割成数组
    const parts = formattedName.split('-');
    const uniqueParts: string[] = [];
    const seenParts = new Set<string>();
    
    // 遍历数组，去除重复的项（保留第一次出现的）
    for (let i = 0; i < parts.length; i++) {
      // 如果当前项之前没有出现过，则添加
      if (!seenParts.has(parts[i])) {
        uniqueParts.push(parts[i]);
        seenParts.add(parts[i]);
      }
    }
    
    // 重新组合成字符串
    formattedName = uniqueParts.join('-');
    
    return formattedName;
  } catch (error) {
    console.error('格式化批次名称失败:', error);
    // 如果格式化失败，返回原始名称
    return batchName;
  }
};


// 处理侧边栏菜单点击
const handleMenuClick = ({ key }: { key: string }) => {
  if (key !== 'no-data') {
    activeTabKey.value = key;
    // 清空复选框
    selectedRowKeys.value = [];
    isEntrustButtonDisabled.value = true;
  }
};


// 获取委托案件列表数据
const fetchEntrustList = async () => {
  loading.value = true;
  try {
    // 获取今日开始和结束时间
    const today = dayjs();
    const todayStart = today.startOf('day').toISOString();
    const todayEnd = today.endOf('day').toISOString();

    const defaultParams = {
      key: "",
      channelFrom: "",
      overdueDayStart: "",
      overdueDayEnd: "",
      productTypeCodes: [],
      states: [],
      disStates: ["INIT"],
      staffIds: [],
      bizLevel: "",
      batchIds: [],
      riskType: "",
      riskIdentification: "",
      lastBackedDateStart: null,
      lastBackedDateEnd: null,
    }

    // 构建请求参数
    const params: GetCaseListParams = {
      current: 1,
      size: 1000, // 获取足够多的数据
      queryType: 'own',
      disStates: ['INIT'],
      loanCreatedStart: todayStart,
      loanCreatedEnd: todayEnd
    };

    Object.assign(params, defaultParams);
    console.log('请求参数:', params);

    const result = await getCaseList(params);

    if (result.success && result.result) {
      const { records } = result.result;
      const allRecords = records || [];

      // 过滤掉包含『南宁小贷』的批次名称数据
      const filteredRecords = allRecords.filter((record: CaseRecord) => {
        const batchName = record.batchName || '';
        return !batchName.includes('南宁小贷');
      });

      casesData.value = filteredRecords;

      // 设置默认激活的Tab
      if (filteredRecords.length > 0) {
        const firstBatchName = filteredRecords[0].batchName || '未分组';
        activeTabKey.value = firstBatchName;
      }

      if (debugMode.value) {
        console.log('获取委托案件列表结果:', {
          原始记录数: allRecords.length,
          过滤后记录数: filteredRecords.length,
          过滤掉的记录数: allRecords.length - filteredRecords.length,
          批次分组: Object.keys(groupedCases.value),
          今日时间范围: { todayStart, todayEnd }
        });
      }

      message.success(`获取委托案件列表成功，共 ${filteredRecords.length} 条记录（已过滤包含"南宁小贷"的数据）`);
    } else {
      message.error('获取委托案件列表失败');
      casesData.value = [];
    }
  } catch (error) {
    console.error('获取委托案件列表失败:', error);
    message.error('网络错误，请稍后重试');
    casesData.value = [];
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const handleRefresh = () => {
  fetchEntrustList();
};

// 页面加载时获取数据
onMounted(() => {
  fetchEntrustList();
});

// 委案
const handleEntrust = () => {
  if (isEntrustButtonDisabled.value) return;

  // 获取当前选中行的loanIds
  const selectedLoanIds = selectedRowKeys.value;

  if (selectedLoanIds.length === 0) {
    message.warning('请选择要委案的数据');
    return;
  }

  // 打开委案弹框
  isEntrustModalVisible.value = true;

  // 请求委案初始化数据
  fetchEntrustInitData(selectedLoanIds);
};

// 获取委案初始化数据
const fetchEntrustInitData = async (loanIds: string[]) => {
  try {
    // 请求countEntrustClient接口
    const countResult = await countEntrustClient({
      loanIds: loanIds,
      tsToken: localStorage.getItem('tsToken') || ''
    });

    if (countResult.success && countResult.result) {
      entrustForm.value.clients = countResult.result.clients || 0;
      entrustForm.value.loans = countResult.result.loans || 0;
      // entrustForm.value.isInvalidRule = countResult.result.ruleSwitch || false;
      entrustForm.value.loanIds = loanIds;
    }

    // 请求委案商列表
    const entrustResult = await getEntrustByAId({
      tsToken: localStorage.getItem('tsToken') || ''
    });

    if (entrustResult.success && entrustResult.result) {
      // 转换数据格式：{customerId, customerName} -> {id, name}
      entrustList.value = (entrustResult.result || []).map((item: any) => ({
        id: item.customerId,
        name: item.customerName
      }));
    }

    // 设置委案批次名称默认值
    const currentGroup = groupedCases.value[activeTabKey.value] || [];
    if (currentGroup.length > 0) {
      const originalBatchName = currentGroup[0].batchName || '';
      // 使用格式化函数处理批次名称，移除日期后面的 "_数字" 部分
      entrustForm.value.batchName = formatBatchName(originalBatchName);
    }

  } catch (error) {
    console.error('获取委案初始化数据失败:', error);
    message.error('获取委案数据失败');
  }
};

// 委案弹框确认
const handleEntrustConfirm = async () => {
  if (!entrustForm.value.entrustBId) {
    message.warning('请选择委案商');
    return;
  }

  if (entrustForm.value.batchOption === 'new' && !entrustForm.value.batchName) {
    message.warning('请输入委案批次名称');
    return;
  }


  try {
    // 构建委案参数
    const entrustParams = {
      entrustBId: entrustForm.value.entrustBId,
      isInvalidRule: entrustForm.value.isInvalidRule,
      loanIds: entrustForm.value.loanIds,
      batchId: entrustForm.value.batchOption === 'select' ? entrustForm.value.batchId : '',
      batchName: entrustForm.value.batchOption === 'new' ? entrustForm.value.batchName : '',
      tsToken: localStorage.getItem('tsToken') || ''
    };

    console.log('委案参数:', entrustParams);

    // 调用委案接口
    const result = await entrustClient(entrustParams);

    if (result.success) {
      message.success('委案成功');
      isEntrustModalVisible.value = false;

      // 清空复选框
      selectedRowKeys.value = [];
      isEntrustButtonDisabled.value = true;

      // 清空表单数据
      entrustForm.value = {
        batchId: '',
        clients: 0,
        loans: 0,
        entrustBId: '',
        batchOption: 'new',
        batchName: '',
        isInvalidRule: true,
        loanIds: []
      };

      // 委案完成后刷新列表
      await fetchEntrustList();

      // 委案完成后执行定时任务
      try {
        const taskSuccess = await executeScheduledTask();
        if (taskSuccess) {
          // 定时任务执行成功后再次刷新列表
          await fetchEntrustList();
        }
      } catch (error) {
        console.error('定时任务执行失败:', error);
        // 定时任务失败不影响委案结果，只记录错误
      }
    } else {
      message.error(result.message || '委案失败');
    }
  } catch (error) {
    console.error('委案失败:', error);
    message.error('委案失败，请稍后重试');
  }
};

// 委案弹框取消
const handleEntrustCancel = () => {
  isEntrustModalVisible.value = false;
  // 清空表单数据
  entrustForm.value = {
    batchId: '',
    clients: 0,
    loans: 0,
    entrustBId: '',
    batchOption: 'new',
    batchName: '',
    isInvalidRule: true,
    loanIds: []
  };
};
</script>

<style scoped>
.entrust-list-container {
  height: 100%;
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  box-sizing: border-box;

  display: flex;
  flex-direction: column;
}

:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-table-wrapper .ant-table .ant-table-title, :where(.css-dev-only-do-not-override-1p3hq3p).ant-table-wrapper .ant-table .ant-table-header) {
  border-radius: 0;
}

:deep(.ant-table-wrapper) {
  height: 100%;
  box-sizing: border-box;
  padding-bottom: 20px;
}

:deep(.ant-card) {
  box-shadow: none;
  border-radius: 0;
}

:deep(.ant-menu) {
  border-inline-end: none !important;
}

:deep(.ant-card-body) {
  padding: 0;
}

/* 粘性侧边栏样式 */
.sticky-sidebar {
  position: sticky;
  top: 0;
  align-self: flex-start;
  z-index: 10;
}

/* 新布局样式 */
.new-layout {
  display: flex;
  gap: 16px;
}

/* 无数据容器样式 */
.no-data-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

/* 侧边栏菜单样式优化 */
.sticky-sidebar :deep(.ant-menu) {
  border-right: none;
}

.sticky-sidebar :deep(.ant-menu-item) {
  margin: 4px 0;
  border-radius: 6px;
}

.sticky-sidebar :deep(.ant-menu-item-selected) {
  background-color: #e6f7ff;
  color: #1890ff;
}

/* 主内容区域样式 */
.w-4\/5 {
  flex: 1;
  min-width: 0;
}

.page-header {
  height: 130px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
}

.header-title h2 {
  margin: 0 0 8px 0;
  color: #262626;
  font-size: 24px;
  font-weight: 600;
}

.header-title h2 span {
  color: #8c8c8c;
  font-size: 16px;
  font-weight: 400;
  margin-left: 8px;
}

.date-range-info {
  margin: 0 0 16px 0;
  color: #8c8c8c;
  font-size: 14px;
}

.color-legend {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #8c8c8c;
}

.legend-color {
  width: 16px;
  height: 12px;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
}

.today-pending-audit-color {
  background-color: #fff2e8;
  border-left: 3px solid #ff7a00;
}

.today-color {
  background-color: #f6ffed;
  border-left: 3px solid #52c41a;
}

.yesterday-color {
  background-color: #fff7e6;
  border-left: 3px solid #fa8c16;
}

.recent-color {
  background-color: #f0f5ff;
  border-left: 3px solid #1890ff;
}

.older-color {
  background-color: #fafafa;
  border-left: 3px solid #d9d9d9;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-section {
  height: calc(100% - 154px);
}

.table-wrapper {
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  border: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
}

.case-count-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  text-align: left;
}

.count-item {
  font-size: 12px;
  line-height: 1.4;
  color: #666;
}

.count-item:first-child {
  color: #1890ff;
  font-weight: 500;
}

/* 今日案件行样式 */
:deep(.today-row) {
  background-color: #f6ffed !important;
  border-left: 4px solid #52c41a;
}

:deep(.today-row:hover) {
  background-color: #f0f9ff !important;
}

/* 今日待审核案件行样式 - 特殊高亮 */
:deep(.today-pending-audit-row) {
  background: linear-gradient(135deg, #fff2e8 0%, #f6ffed 100%) !important;
  border-left: 4px solid #ff7a00;
  box-shadow: 0 2px 8px rgba(255, 122, 0, 0.15);
  position: relative;
}

:deep(.today-pending-audit-row:hover) {
  background: linear-gradient(135deg, #ffe7ba 0%, #f0f9ff 100%) !important;
  box-shadow: 0 4px 12px rgba(255, 122, 0, 0.25);
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 今日待审核案件特殊标识 */
:deep(.today-pending-audit-row::before) {
  content: '⚠️';
  position: absolute;
  left: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  z-index: 1;
}

/* 昨日案件行样式 */
:deep(.yesterday-row) {
  background-color: #fff7e6 !important;
  border-left: 4px solid #fa8c16;
}

:deep(.yesterday-row:hover) {
  background-color: #fffbe6 !important;
}

/* 近3日案件行样式 */
:deep(.recent-row) {
  background-color: #f0f5ff !important;
  border-left: 4px solid #1890ff;
}

:deep(.recent-row:hover) {
  background-color: #e6f7ff !important;
}

/* 更早案件行样式 */
:deep(.older-row) {
  background-color: #fafafa !important;
  border-left: 4px solid #d9d9d9;
}

:deep(.older-row:hover) {
  background-color: #f5f5f5 !important;
}

/* 无日期案件行样式 */
:deep(.no-date-row) {
  background-color: #fff2f0 !important;
  border-left: 4px solid #ff4d4f;
}

:deep(.no-date-row:hover) {
  background-color: #fff1f0 !important;
}

/* 无效日期案件行样式 */
:deep(.invalid-date-row) {
  background-color: #f9f0ff !important;
  border-left: 4px solid #722ed1;
}

:deep(.invalid-date-row:hover) {
  background-color: #f4f0ff !important;
}

/* 表格行悬停效果优化 */
:deep(.ant-table-tbody > tr:hover > td) {
  background-color: inherit !important;
}


:deep(.ant-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;

  .ant-tabs-nav {
    margin-bottom: 0;
    flex-shrink: 0;
  }

  .ant-tabs-content-holder {
    height: calc(100% - 36px);
    box-sizing: border-box;
    padding: 0;
    overflow: hidden;
  }

  .ant-tabs-tabpane {
    height: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
}

/* 客户信息样式 */
.customer-info {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.customer-name {
  font-weight: 500;
  color: #1a1a1a;
  margin-bottom: 4px;
}

.customer-mobile {
  font-size: 12px;
  color: #666;
}

/* 期数信息样式 */
.period-info {
  text-align: center;
  font-size: 12px;
  line-height: 1.4;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.period-info div {
  margin-bottom: 2px;
}

/* 金额信息样式 */
.amount-info {
  text-align: center;
  font-size: 12px;
  line-height: 1.4;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.amount-info div {
  margin-bottom: 2px;
}

.amount-info div:first-child {
  font-weight: 500;
  color: #ff4d4f;
}

/* Tab样式优化 */
:deep(.ant-tabs-tab) {
  padding: 8px 16px;
  margin-right: 8px;
}

:deep(.ant-tabs-tab-active) {
  background-color: #f0f9ff;
  border-radius: 4px;
}

/* 表格样式优化 */
:deep(.ant-table) {
  height: calc(100% - 36px) !important;
}

:deep(.ant-table-container) {
  height: calc(100% - 36px) !important;
}

:deep(.ant-table-body) {
  overflow-y: auto !important;
  max-height: calc(100vh - 300px) !important;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
  text-align: center;
  vertical-align: middle;
  position: sticky;
  top: 0;
  z-index: 10;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 8px 6px;
  text-align: center;
  vertical-align: middle;
  font-size: 12px;
}

/* 刷新按钮美化 */
:deep(.ant-btn-primary) {
  background-color: #1890ff;
  border-color: #1890ff;
}

:deep(.ant-btn-primary:hover) {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .entrust-list-container {
    padding: 16px;
  }

  .page-header {
    padding: 16px;
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .header-title h2 {
    font-size: 20px;
  }

  .color-legend {
    gap: 12px;
  }

  .legend-item {
    font-size: 12px;
  }
}

/* a-affix 居中样式 */
.affix-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 16px;
}

/* 委案弹框标题居中 */
:deep(.ant-modal-header) {
  text-align: center;
}

:deep(.ant-modal-title) {
  text-align: center;
  font-weight: 600;
}

/* 空数据页面样式 */
.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 40px 20px;
}

.empty-description {
  font-size: 16px;
  color: #666;
  font-weight: 500;
}

.empty-tip {
  margin: 8px 0 0 0;
  font-size: 14px;
  color: #999;
  line-height: 1.5;
}
</style>
